/*
 * umlapi 1.1.2
 * UML API 
 * Copyright (C) 2003  Pavel Vlasov
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * URL: http://www.pavelvlasov.com/Products/UmlApi/index.html
 * e-Mail: vlasov@pavelvlasov.com

 */
package com.pavelvlasov.uml.xmi;

import java.util.StringTokenizer;

import com.pavelvlasov.uml.Acceptor;
import com.pavelvlasov.uml.ModelElement;
import com.pavelvlasov.uml.TaggedValue;
import com.pavelvlasov.uml.UmlException;

/**
 * @author Pavel Vlasov	
 * @version $Revision$
 */
public class PhaseAcceptor implements Acceptor {
	private int[] phase;

	/**
	 * @param phase Phase. Should be in <number>[.<number>]* notation. Accepts only elements with equal or lower phase.
	 */
	public PhaseAcceptor(String phase) throws UmlException {
		this.phase=parsePhase(phase);
	}

	/* (non-Javadoc)
	 * @see com.pavelvlasov.uml.Acceptor#accept(com.pavelvlasov.uml.ModelElement)
	 */
	public boolean accept(ModelElement element) {
		TaggedValue ptv=element.getToolTaggedValues().getValue("phase");
		if (ptv==null) {
			return false;
		}
		
		try {
			int[] ephase=parsePhase(ptv.getValue());
			for (int i=0; i<phase.length; i++) {
				if (ephase.length<=i) {
					return false;
				} else {
					if (phase[i]>ephase[i]) {
						return true;
					} else if (phase[i]<ephase[i]) {
						return false;
					}						
				}
			} 
		} catch (UmlException e) {
			System.err.println("Invalid phase format '"+ptv.getValue()+"'for element "+element.getAbsoluteName()+" ["+element.getId()+"]");
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	private int[] parsePhase(String phase) throws UmlException {
		StringTokenizer st=new StringTokenizer(phase, ".");
		int[] ret=new int[st.countTokens()];
		int idx=0;
		while (st.hasMoreTokens()) {
			try {
				ret[idx++]=Integer.parseInt(st.nextToken());
			} catch (NumberFormatException e) {
				throw new UmlException("Invalid phase format: "+phase, e);
			}
		}
		return ret;
	}
}
